<template>
	<view class="container">
		<view class="fl-cc">
			<!-- 导航模块 -->
			<view v-if="parkingInfo.length > 0" class="parking-con">
				<!-- 搜索 -->
				<view class="search-btn pdlr">
					<uni-search-bar class="uni-mt-10" radius="5" placeholder="自动显示隐藏" clearButton="auto" cancelButton="none" @confirm="search" />
				</view>
				<parkingMap :parking-spots="[
  { id: 1, number: 32, latitude: 34.341317, longitude: 108.93965 },
  { id: 2, number: 3, latitude: 34.342534, longitude: 108.941084 },
  { id: 3, number: 0, latitude: 34.341176, longitude: 108.940518 }
]" @update="mapUpdate" @onClickMarker="onClickMarker" />
			</view>
			<view v-else class="stext pd bgwhite">附近暂无停车场！</view>
		</view>
		<view ref="isShowParkingRef" class="bottom-float-card" v-show="isShowParking">
			<view class="pdtb5 fl-cc w100" @click="isShowParking = false"><view class="close-float-btn"></view></view>
			<view class="pdb pdlr">
				<ParkingCard :parkingInfo="cu_parkingInfo" />
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		reactive,
		nextTick
	} from 'vue';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		useStore
	} from '@/ya/store';
	import ParkingCard from '@/pages/parking/ParkingCard.vue';
	import parkingMap from "@/components/parkingMap.vue";
	const userStore = computed(() => useStore('user'));
	const loginType = computed(() => parseInt(userStore.value.loginType));
	// 用户位置信息
	const userLocation = computed(() => userStore.value.userLocation);
	// 停车信息
	const examId = ref();
	const isShowParking = ref(true);
	const isShowParkingRef = ref();
	const parkingInfo = ref([{
		// 折叠态基础信息
		title: '神舟四路（飞天路-航拓路）东侧',
		distanceTag: '距您最近的停车场',
		starIcon: '/static/star.png', // 实际替换为你的收藏图标路径
		address: '308米·神舟四路（飞天路-航拓路）东侧',
		statusBg: '#87d068',
		statusText: '余位充足 空32/总32',
		typeBg: '#f5c882',
		typeText: '路边停车场'},
		{
		id: 1,
		// 折叠态基础信息
		title: '神舟四路（飞天路-航拓路）东侧',
		distanceTag: '距您最近的停车场',
		starIcon: '/static/star.png', // 实际替换为你的收藏图标路径
		address: '308米·神舟四路（飞天路-航拓路）东侧',
		statusBg: '#87d068',
		statusText: '余位充足 空32/总32',
		typeBg: '#f5c882',
		typeText: '路边停车场',

		// 展开态信息
		expandTitle: '神舟四路（飞天路-航拓路）东侧',
		expandAddress: '神舟四路（飞天路-航拓路）东侧',
		expandTagBg1: '#f5c882',
		expandTagText1: '地面停车场',
		expandTagBg2: '#b3e5fc',
		expandTagText2: '距您1.1公里',
		expandTagBg3: '#e1f5fe',
		expandTagText3: '空车位10/42总车位',
		feeInfo: {
			parkNo: '1-01-2-3023',
			zoneType: '二类区',
			parkCount: '26',
			parkName: '鲁家村南巷',
			feeBase: '市政发[2019]14号',
			feeMode: '计时收费（政府定价）',
			feeList: [{
				period: '高峰时段',
				time: '08:00-10:00',
				fee: '2元/30分钟'
			}]
		}
	}]);
	const cu_parkingInfo = ref(parkingInfo.value[0]);
	// 导航信息
	const navSiteInfo = reactive({
		distance: 0,
		duration: 0,
		onFootTime: 0,
		onTaxiTime: 0,
	});
	// 修改数据获取方式
	const getExamDetail = async (eid) => {
		try {
		} catch (e) {
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
		}
	}
	const back = () => {
		uni.navigateBack()
	};
	// 加载后就获取位置签到
	onLoad(async (query) => {
		console.log('query', query);
		const {
			eid
		} = query;
		if (eid) {
			examId.value = eid;
		}
		await nextTick();
		isShowParking.value = true;
		// isShowParkingRef.value.open('bottom');
	});
	onShow(async () => {
	});
	const onClickMarker = (e) => {
		// cu_parkingInfo.value = {
		// 	...e
		// }
		cu_parkingInfo.value = parkingInfo.value[1];
		isShowParking.value = true;
		// isShowParkingRef.value.open('bottom');
	};
	// 地图数据更新
	const mapUpdate = (dist, results, site) => {
		console.log('mapUpdate:', dist, results);
		// 保留原始距离计算
		navSiteInfo.distance = Math.round(dist);
		// userStore.value.updateLocation(site);
		// 新增精确耗时计算（优先使用API返回数据）
		try {
			// 步行耗时（分钟）：使用API返回时间或计算值
			navSiteInfo.onFootTime = results?.[0]?.routes?.[0]?.duration ||
				Math.round(dist / 1.4 / 60); // 1.4m/s 步行速度

			// 驾车耗时（分钟）：使用API返回时间或计算值
			navSiteInfo.onTaxiTime = results?.[1]?.routes?.[0]?.duration ||
				Math.round(dist / 13.9 / 60); // 13.9m/s 城市道路均速
		} catch {
			// API数据异常时回退基础计算
			navSiteInfo.onFootTime = Math.round(dist / 80);
			navSiteInfo.onTaxiTime = Math.round(dist / 800);
		}

		// 设置最小时间阈值
		navSiteInfo.onFootTime = Math.max(1, navSiteInfo.onFootTime);
		navSiteInfo.onTaxiTime = Math.max(1, navSiteInfo.onTaxiTime);
		console.log('navSiteInfo', navSiteInfo);
	};
	// 打开外部地图应用
	function openExternalMapApp(mapType) {
		// 坐标系转换
		const convertCoord = (lat, lon) => {
			console.log('convertCoord：>', lat, lon);
			// 调用后端接口或使用转换算法
			return {
				latitude: lat,
				longitude: lon
			};
		};

		// 生成导航链接
		const origin = convertCoord(userLocation.value.latitude, userLocation.value.longitude);
		const destination = convertCoord(parkingInfo.value.kdy, parkingInfo.value.kdx);
		console.log('导航：>', origin, '-----' + destination);
		const name = parkingInfo.value.kdName + parkingInfo.value.floorName;
		const address = parkingInfo.value.kdAddress + '- 考点编号：' + parkingInfo.value.kdCode;

		let url = "";
		switch (mapType) {
			case "gaode":
				url =
					`amapuri://route/plan/?slat=${origin.latitude}&slon=${origin.longitude}&sname=当前位置&dlat=${destination.latitude}&dlon=${destination.longitude}&dname=${encodeURIComponent(name)}&dev=0&t=0`;
				break;
			case "baidu":
				url =
					`baidumap://map/direction?origin=${origin.latitude},${origin.longitude}&destination=${destination.latitude},${destination.longitude}&destination=${encodeURIComponent(name)}&coord_type=wgs84&mode=driving`;
				break;
			case "tencent":
				url =
					`qqmap://map/routeplan?type=drive&fromcoord=${origin.latitude},${origin.longitude}&to=${encodeURIComponent(name)}&tocoord=${destination.latitude},${destination.longitude}`;
				break;
			default:
				uni.showToast({
					title: "不支持的地图类型",
					icon: "none"
				});
				return;
		}

		uni.openURL({
			url,
			success() {
				console.log("成功调起地图应用");
			},
			fail(err) {
				uni.showToast({
					title: `调起失败: ${err.errMsg}`,
					icon: "none"
				});
				openLocation(parkingInfo.value);
			}
		});
	};
	// 启动外部导航
	const startExternalNav = () => {
		openLocation(parkingInfo.value);
		// 打开导航选择菜单
		// uni.showActionSheet({
		// 	itemList: ['高德地图', '百度地图', '腾讯地图'],
		// 	success(res) {
		// 		const mapTypes = ["gaode", "baidu", "tencent"];
		// 		const selectedType = mapTypes[res.tapIndex];
		// 		// openExternalMapApp(selectedType);
		// 	}
		// });
	};
	const openLocation = (item) => {
		// 调用【跨端】地图API打开定位
		uni.openLocation({
			latitude: Number(item.kdy),
			longitude: Number(item.kdx),
			scale: 18, // 缩放级别，取值范围为5~18  
			name: item.kdName + item.floorName, // 可选，位置名称  
			address: item.kdAddress + '- 考点编号：' + item.kdCode // 可选，位置详细描述  
		});
	};
</script>

<style lang="scss" scoped>
	.container {
		background-color: #FFFFFF;
		padding: 0px;
		margin: 0px;
		// background: linear-gradient(#19C6AD 180px, #F5F5F5 150px);
		position: relative;
	}
	.parking-con{
		position: relative;
		.search-btn{
			top: 10px;
		}
	}
	.bottom-float-card{
		bottom: 64rpx;
		position: absolute;
		background-color: #FFFFFF;
		width: 100vw;
		z-index: 2;
		border-radius: 10px 10px 0px 0px;
	}
	.close-float-btn{
		width: 100rpx;
		height: 3px;
		border-radius: 5px;
		background-color: #ccc;
	}
</style>